import axios from "axios";
import axiosRetry from "axios-retry";
import lodash from "lodash";
const { get } = lodash;

function createService(defaultConfig) {
  // 创建一个 axios 实例
  const service = axios.create(defaultConfig);
  // 请求拦截
  service.interceptors.request.use(
    (config) => {
      if (global.cookie) {
        config.headers.Cookie = global.cookie;
      }
      if (global.unieap) {
        config.params = {
          method: "post",
          browserUser: unieap.loginAccount,
          browserOrg: unieap.orgId,
        };
      }
      return config;
    },
    (error) => {
      // 发送失败
      console.error(error);
      return Promise.reject(error);
    }
  );
  // 响应拦截
  service.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      const status = get(error, "response.status");
      switch (status) {
        case 302:
          return Promise.resolve(error.response);
        case 400:
          error.message = "请求错误";
          break;
        case 401:
          error.message = "未授权，请登录";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`;
          break;
        case 408:
          error.message = "请求超时";
          break;
        default:
          break;
      }
      console.error(error);
      return Promise.reject(error);
    }
  );

  axiosRetry(service, {
    retries: 10,
    shouldResetTimeout: true,
    retryDelay: (retryCount) => {
      return retryCount * 1000;
    },
  });

  return service;
}

export function createRequestFunction({ baseURL } = {}) {
  return (config) => {
    const configDefault = {
      headers: {
        "Content-Type": "application/json",
      },
      timeout: 10000,
      baseURL,
      withCredentials: true,
    };
    return createService(Object.assign(configDefault, config));
  };
}

// 因为eslint原因，后面去掉createService
// export { createService, createRequestFunction };
